﻿Imports Microsoft.Xna.Framework.Audio
Imports Microsoft.Xna.Framework.Graphics
Imports System.Runtime.CompilerServices
Imports System.IO
Imports Runa.Common.Helper
Imports System.Reflection

Namespace Global.Runa.Resources.ContentManagers

    Public Class ResourceStreamContentManager
        Inherits BasicContentManager

        Public Property RootPath() As String
        Public Property Assembly() As Assembly

        Public Sub New(serviceProvider As System.IServiceProvider)
            MyBase.New(serviceProvider)
            Me.RootDirectory = ""
            Me.Assembly = Me.GetType().Assembly
        End Sub

        Public Sub New(serviceProvider As System.IServiceProvider, rootDirectory As String)
            MyBase.New(serviceProvider, rootDirectory)
            Me.RootDirectory = rootDirectory
            Me.Assembly = Me.GetType().Assembly
        End Sub

        Public Sub New(serviceProvider As System.IServiceProvider, rootDirectory As String, ByVal asm As Assembly)
            MyBase.New(serviceProvider, rootDirectory)
            Me.RootDirectory = rootDirectory
            Me.Assembly = asm
        End Sub

        Public Overrides Function Exists(ByVal assetName As String) As Boolean
            Dim asm = Me.Assembly
            Dim resources = asm.GetManifestResourceNames()
            Dim fullName = String.Format("{0}.{1}", Me.RootDirectory, assetName)
            Return resources.Contains(fullName)
        End Function

        Protected Overrides Function OpenStream(assetName As String) As System.IO.Stream
            Dim asm = Me.Assembly
            Dim fullName = String.Format("{0}.{1}", Me.RootDirectory, assetName)
            Dim resources = asm.GetManifestResourceNames()
            If Me.Exists(assetName) Then
                Return asm.GetManifestResourceStream(fullName)
            Else
                Throw New FileNotFoundException(String.Format("File {0} not found.", fullName))
            End If
        End Function

    End Class

End Namespace